﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.IO;
using System.Net;

using ScrumTable.Common;
using ScrumTable.Common.Logging;
using ScrumTable.Common.Security;
using ScrumTable.Common.Text;

#endregion

namespace ScrumTable.DL.Data.Common.Serialization
{
    /// <summary>
    /// Represents the data resolver for data serialization or deserialization.
    /// </summary>
    public class DataResolver : IDataResolver
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        private const string RequestMethod = "GET";
        private const int RequestTimeout = 20000; // ms

        private const string SrcBegin = "SRC=\"";
        private const string SrcEnd = "\"";

        private readonly ConnectionInformation _connectionCtx;

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new DataResolver instance.
        /// </summary>
        public DataResolver(ConnectionInformation information)
        {
            PreCondition.AssertNotNull(information, "information");

            _connectionCtx = information;
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Saves the specified uri to download into the given directory and
        /// returns the new relative url on the local storage.
        /// </summary>
        /// <param name="recommendedPath">Specifies the file and directory where local data can be stored.</param>
        /// <param name="toDownload">Specifies the url to resolve.</param>
        /// <returns>Returns an url which points to the data on the local storage.</returns>
        public Uri ResolveTo(string recommendedPath, Uri toDownload)
        {
            try
            {
                return ResolveToSave(
                    recommendedPath + Path.GetExtension(toDownload.ToLocalPath()),
                    toDownload);
            }
            catch (Exception e)
            {
                Logger<DataResolver>.Warn("File with url could not be resolved.", e);
                return UriUtil.Empty;
            }
        }

        private Uri ResolveToSave(string recommendedOutputFilePath, Uri toDownload)
        {
            if (toDownload.IsFile)
            {
                return SaveFormFilePath(recommendedOutputFilePath, toDownload);
            }
            else
            {
                return SaveFromWeb(recommendedOutputFilePath, toDownload);
            }
        }

        private Uri SaveFormFilePath(string recommendedOutputFilePath, Uri toDownload)
        {
            string pathToDownload = toDownload.ToLocalPath();

            if (pathToDownload != recommendedOutputFilePath
                && !pathToDownload.StartsWith(Path.GetDirectoryName(recommendedOutputFilePath)) /* already stored in data directory */)
            {
                File.Copy(
                    toDownload.ToLocalPath(),
                    recommendedOutputFilePath,
                    true);

                return new Uri(
                    Path.GetFileName(recommendedOutputFilePath),
                    UriKind.RelativeOrAbsolute);
            }
            return toDownload;
        }

        private Uri SaveFromWeb(string recommendedOutputFilePath, Uri toDownload)
        {
            string execDir = Path.GetDirectoryName(GetType().Assembly.Location);

            // first try to download document. if it is an html, the sub file uri is returned
            Uri subFileUri = TryStoreFileWithHtml(ref recommendedOutputFilePath, toDownload);

            if (subFileUri != null)
            {
                // store sub file to file system
                TryStoreFile(ref recommendedOutputFilePath, subFileUri);
            }

            // replace relative path if available
            if (recommendedOutputFilePath.StartsWith(execDir))
            {
                return new Uri(recommendedOutputFilePath.Substring(execDir.Length + 1), UriKind.RelativeOrAbsolute);
            }
            return new Uri(recommendedOutputFilePath.Substring(recommendedOutputFilePath.Length + 1), UriKind.RelativeOrAbsolute);
        }

        private Uri TryStoreFileWithHtml(ref string filePath, Uri toDownload)
        {
            Uri subFile = null;
            WebRequest request = WebRequest.Create(toDownload);
            request.Credentials = _connectionCtx.NetworkCredentials;
            request.Method = RequestMethod;
            request.Timeout = RequestTimeout;
          
            using (WebResponse response = request.GetResponse())
            {
                if (IsHtml(response.ContentType))
                {
                    subFile = DownloadAndParseHtmlFile(response.GetResponseStream());
                }
                else
                {
                    filePath = Path.ChangeExtension(filePath, GetExtension(response.ContentType));
                    DownloadFile(filePath, response.GetResponseStream());
                }
            }
            return subFile;
        }

        private void TryStoreFile(ref string filePath, Uri toDownload)
        {
            WebRequest request = WebRequest.Create(toDownload);
            request.Credentials = _connectionCtx.NetworkCredentials;
            request.Method = RequestMethod;
            request.Timeout = RequestTimeout;

            using (WebResponse response = request.GetResponse())
            {
                filePath = Path.ChangeExtension(filePath, GetExtension(response.ContentType));
                DownloadFile(filePath, response.GetResponseStream());
            }
        }

        private Uri DownloadAndParseHtmlFile(Stream toProcess)
        {
            using (StreamReader reader = new StreamReader(toProcess))
            {
                string webData = reader.ReadToEnd();

                if (!string.IsNullOrEmpty(webData))
                    webData = webData.CutOff(SrcBegin, SrcEnd);
                return new Uri(webData);
            }
        }

        private void DownloadFile(string filePath, Stream toProcess)
        {
            using (Stream remoteStream = toProcess)
            {
                using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                {
                    byte[] buffer = new byte[1024]; // 1 kByte buffer
                    int bytesRead;

                    do
                    {
                        bytesRead = remoteStream.Read(buffer, 0, buffer.Length);
                        fileStream.Write(buffer, 0, bytesRead);
                    }
                    while (bytesRead > 0);
                }
            }
        }

        private bool IsHtml(string contentType)
        {
            return (contentType == "text/html");
        }

        private string GetExtension(string contentType)
        {
            switch (contentType)
            {
                case "image/jpeg":
                    return "jpg";
                case "image/gif":
                    return "gif";
                case "image/x-png":
                case "image/png":
                    return "png";
                default:
                    return "bin";
            }
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion

    }
}